Vue Checkbox Disabled After Checked: In Vue, a checkbox can be disabled after being checked by using a combination of the v-model and :disabled directives. When the checkbox is initially checked, the v-model is set to true and the :disabled directive is also set to true. This disables the checkbox and prevents the user from unchecking it.
This functionality can be useful in situations where a user needs to make a one-time selection or when certain conditions must be met before the user can proceed. By disabling the checkbox after it has been checked, the user is prevented from changing their selection and the application can enforce its business rules.
How can I disable a Vue checkbox after it has been checked?
This code creates a Vue application that renders a checkbox. When the checkbox is checked, the text “Checked” is displayed, otherwise “Unchecked” is displayed. Additionally, a watch
is used to disable the checkbox when it is checked. The data
object contains two properties: isChecked
and isDisabled
, both of which are initialized to false
. The v-model
directive binds the isChecked
property to the checkbox’s checked state, and the v-bind:disabled
directive binds the isDisabled
property to the checkbox’s disabled state.
When the isChecked
property is updated (i.e., when the checkbox is checked or unchecked), the watch
function is triggered. If isChecked
is true
, the isDisabled
property is set to true
, which disables the checkbox.
Vue Checkbox Disabled After Checked Example
<div id="app">
<input type="checkbox" v-model="isChecked" v-bind:disabled="isDisabled">{{isChecked?'Checked':'Uncheck'}}
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
isChecked: false,
isDisabled: false
}
},
watch: {
isChecked() {
if (this.isChecked) {
this.isDisabled = true;
}
}
}
});
app.mount('#app');
</script>